import Taro from '@tarojs/taro'
import {set as setGlobalData, get as getGlobalData } from '../static/js/global_data'
import base from '../static/js/base'
import api from './api'
import lyServce from '../lyService'

module.exports = {
        getLoginState,
        commonLogin,
        getOpenid,
        // getUserId,
        weappLogin,
        weappLoginModify,
        accountLogin,
        getUserInfo,
        getShopInfo,
        tabList,
        getGoodList,
        getCategory,
        getGoodDetail,
        getGoodDetailLvgg,
        changeCar,
        delCart,
        getCartNum,
        getUserCart,
        setCartList,
        getOrderDetail,
        getOrderPrices,
        payment,
        getAddressList,
        addressAdd,
        addressDefault,
        getAddress,
        getExchangeList,
        getPintuanList,
        subscribe,
        getCode,
        comNavTo,
    }
    // 获取登陆状态
function getLoginState(that, callback) {
    const loginState = Taro.getStorageSync('loginState')
        // if(callback){callback(data)}
    if (loginState) { //登陆过
        that.setState({ isLoginState: loginState })
    } else { //没登陆过
        const isLoginState = getGlobalData('isLoginState')
        that.setState({ isLoginState: isLoginState })
    }
}
// 微信，支付宝登陆
function commonLogin(callback) {
    base.getExtConfig(() => {
        let evn = process.env.TARO_ENV;
        base.login((code) => {
                const loginType = Taro.getStorageSync('loginType')
                if (!loginType) { //未登陆
                    if (evn == 'weapp') { // 微信
                        if (code) {
                            getOpenid(code, (openid) => {
                                // sensors.setOpenid(openid);
                                weappLogin(openid, () => {
                                    // sensors.login(getGlobalData('C_MB_NO'));
                                    console.log(getGlobalData('C_MB_NO')) //会员编号
                                    base.setSensorsCommonParse(callback)
                                })
                            })
                        } else {
                            const openid = Taro.getStorageSync('openid')
                                //sensors.setOpenid(openid);
                            weappLogin(openid, () => {
                                //sensors.login(getGlobalData('C_MB_NO'));
                                base.setSensorsCommonParse(callback)
                            })
                        }
                    } else { // 支付宝
                        console.log('com1')
                        if (callback) { callback() }
                    }
                } else { //已登陆
                    const openid = Taro.getStorageSync('openid')
                    weappLogin(openid, () => {
                        if (evn == 'weapp') {
                            if (callback) { callback() }
                            base.setSensorsCommonParse(callback)
                            getUserInfo(this)
                        } else { //支付宝
                            base.setSensorsCommonParse(callback)
                            console.log('com2')
                            getUserInfo(this, callback)
                        }

                    })
                }
            })
            // 店铺信息
        getShopInfo(() => {
            base.setSensorsCommonParse()
        })
    })
}
// 获取微信openid
function getOpenid(code, callback) {
    const str = `ShopNo&code`
    let params = {
        bNo: 1508,
        code: code,
    }
    api.get(str, params).then((res) => {
        console.log(res)
    }).catch((err) => {
        console.log(err)
        if (callback) { callback(err.openid) }
        Taro.setStorageSync('openid', err.openid)
        setGlobalData('openid', err.openid)
    })
}
// 微信登陆、注册
function weappLogin(openid, callback) {
    const str = `openid&ShopNo`
    let params = {
        bNo: 107,
        openid: openid,
    }
    if (getGlobalData('JRE') == 'weapp') {
        params.type = 2 //1.微信公众号， 2.微信小程序，3.支付宝小程序
    } else if (getGlobalData('JRE') == 'alipay') {
        params.type = 3
    }
    api.get(str, params).then((res) => {
        Taro.setStorageSync('userInfo', res.mebinfo[0])
        setGlobalData('C_MB_NO', res.mebinfo[0].C_MB_NO)
        setGlobalData('userInfo', res.mebinfo[0])
        if (callback) { callback(res.mebinfo[0]) }
    })
}
// 微信登陆修改账户信息
function weappLoginModify(userInfo, detail, callback) {
    let headImg = null
    console.log(detail)
    if (detail) {
        if (detail.avatarUrl) {
            headImg = detail.avatarUrl
        }
        if (detail.avatar) {
            headImg = detail.avatar
        }
    }
    const str = `mebno&ShopNo&headImg&NickName&isweburl`
    const params = {
        bNo: "1711",
        mebno: userInfo.C_MB_NO,
        headImg: headImg || '',
        NickName: detail ? detail.nickName : ''
    }
    api.get(str, params).then((res) => {
            if (callback) {
                callback()
            } else {
                getUserInfo()
            }
        })
        // api.get(str, params, function (res) {
        //     if (callback) {
        //         callback()
        //     } else {
        //         getUserInfo()
        //     }
        // })
}
// 手机号登陆
function accountLogin(that, openId) {
    const str = `userName&userPwd&ShopNo`
    let params = {
        bNo: 104,
        userName: this.data.username,
        userPwd: this.data.pwd,
        openId: openId,
        type: 2,
    }
    api.get(str, params, function(res) {
        console.log(res)
    })
}
// 获取会员信息
function getUserInfo(that, callback) {
    const userInfo = Taro.getStorageSync('userInfo')
    if (!userInfo) {
        return
    }
    const str = `mebno&ShopNo`
    let params = {
        bNo: 301,
        mebno: userInfo.C_MB_NO,
    }
    api.get(str, params).then((res) => {
        console.log(res)
        res.member.progress = 0 //会员资料完善百分比
        if (res.member.C_MB_PIC) {
            if (res.member.C_MB_PIC.indexOf("http") == -1) {
                res.member.C_MB_PIC = getGlobalData('domainImg') + res.member.C_MB_PIC
            }
            res.member.progress += 25
        }
        if (res.member.D_MB_BIRTHDAY) {
            res.member.D_MB_BIRTHDAY = res.member.D_MB_BIRTHDAY.substr(0, 10)
            res.member.progress += 25
        }
        if (res.member.C_MB_NAME) { res.member.progress += 25 }
        if (res.member.C_MB_SEX) { res.member.progress += 25 }
        // console.log(res.member)
        setGlobalData('userInfo', res.member)
        Taro.setStorageSync('userInfo', res.member)
        if (callback) { callback(res.member) }
    })
}
// 获取店铺信息
function getShopInfo(callback) {
    const str = `ShopNo`
    let params = {
        bNo: '203',
    }
    api.get(str, params, (res) => {
        setGlobalData('shopInfo', res)
        setGlobalData('mainShopNo', res.model.c_pshop_no)
            // res.model.n_yjhid = 390
            // res.model.n_yjhid = 2626
        res.model.n_yjhid = 316
        setGlobalData('industry', res.model.n_yjhid) //  316餐饮1  2626零售2  390美业3
        if (callback) { callback(res) }
    })
}
// 获取导航信息
function tabList(that, callback) {
    const ShopNav = getGlobalData('ShopNav')
    if (ShopNav) {
        if (callback) { callback(ShopNav) }
        return
    }
    const str = `ShopNo&stype&top`
    let params = {
        bNo: 205,
        stype: 0,
        top: 0
    }
    api.get(str, params, function(res) {
        res.ShopNav.map(function(item, i) {
            if (item.C_Link.indexOf("index") != -1 || item.C_Link.indexOf("category") != -1 || item.C_Link.indexOf("personal") != -1 || item.C_Link.indexOf("newsList") != -1) {
                item.navigateType = false;
            } else {
                if (item.C_Link.indexOf("branchshop") != -1) {
                    item.C_Link = "/pages/chooseShop/chooseShop";
                }
                if (item.C_Link.indexOf("integrallist") != -1) {
                    item.C_Link = "/pages/scoreHistory/scoreHistory";
                }
                item.navigateType = true;
            }
            if (item.NavType == 1) {
                item.C_Navigation_ICO = getGlobalData('domainImg') + item.C_Navigation_ICO
            }
        })
        setGlobalData('ShopNav', res.ShopNav)
        if (callback) { callback(res.ShopNav) }
    })
}
// 获取商品列表
function getGoodList(that, callback) {
    const userInfo = Taro.getStorageSync('userInfo')
    const str = `pageindex&pagesize&cid&name&ShopNo`
    let params = {
        bNo: '702b',
        pageindex: that.state.pageindex,
        pagesize: getGlobalData('pagesize'),
        cid: that.state.cid || '',
        name: that.state.name || '',
        cname: that.state.cname || '',
        sort: that.state.sort || "t.ID desc",
        desc: that.state.desc || "",
        iscollect: that.state.iscollect || '-1',
        mebno: userInfo ? userInfo.C_MB_NO : ''
    }

    api.get(str, params).then((res) => {
            let goodLists = []
                // console.log(res)
            if (!res.goodsList) { res.goodsList = [] }
            res.goodsList.map((item) => {
                item.activejson = JSON.parse(item.activejson)
                item.activejsonObj = item.activejson.length > 0 ? item.activejson[0] : null
            })
            that.state.hasEd = res.goodsList.length < getGlobalData('pagesize') ? true : false
            goodLists = that.state.pageindex == 1 ? res.goodsList : that.state.goodList.concat(res.goodsList)
            if (callback) { callback(goodLists, that.state.hasEd, res) }
        }).catch((err) => {
            Taro.hideLoading()
            if (err.msg) {
                base.showModal(err.msg, 'none')
                that.setState({
                    goodList: [],
                    hasList: true
                })
            }


        })
        // api.get(str, params, function (res) {
        //     if(!res.goodsList){res.goodsList = []}
        //     res.goodsList.map((item) => {
        //         item.activejson = JSON.parse(item.activejson)
        //         item.activejsonObj = item.activejson.length > 0 ? item.activejson[0] : null
        //     })

    //     that.state.hasEd = res.goodsList.length < getGlobalData('pagesize') ? true : false
    //     goodLists = that.state.pageindex == 1 ? res.goodsList : that.state.goodList.concat(res.goodsList)
    //     if (callback) { callback(goodLists, that.state.hasEd, res) }
    // }, function (res) {
    //     Taro.hideLoading()
    //     base.showModal(res.msg, 'none')
    //     that.setState({
    //          goodList: goodLists,
    //          hasList: true
    //     })
    // })
}
// 获取商品分类
function getCategory(that, callback) {
    const str = `ShopNo`
    let params = {
        bNo: 704,
    }
    api.get(str, params).then((res) => {
        if (callback) { callback(res.goodscate) }
    })
}
// 获取商品详情
function getGoodDetail(that, gid, callback) {
    let str = `gid&ShopNo`
    let params = {
        bNo: 701,
        gid: gid,
        isGoodsImg: "1",
        isgroupshop: that.state.isgroupshop || '0',
        mebno: getGlobalData('C_MB_NO'), //用户信息id
    }
    api.get(str, params).then((res) => {
        if (res.lvgg) { //规格
            res.goods[0].C_SPID = res.goods[0].C_SPID.split("_")
            for (let i = 0; i < res.lvgg.length; i++) {
                for (let j = 0; j < res.lvgg[i].SpvList.length; j++) {
                    res.lvgg[i].SpvList[j].select = false
                    if (res.goods[0].C_SPID[i] == res.lvgg[i].SpvList[j].N_SPV_ID) {
                        res.lvgg[i].SpvList[j].select = true
                    }
                }
            }
            if (res.goods[0].C_SPID.length == 1) {
                that.setState({
                    Spv1: res.goods[0].C_SPID[0]
                })
            } else if (res.goods[0].C_SPID.length == 2) {
                that.setState({
                    Spv1: res.goods[0].C_SPID[0],
                    Spv2: res.goods[0].C_SPID[1]
                })
            } else if (res.goods[0].C_SPID.length >= 3) {
                that.setState({
                    Spv1: res.goods[0].C_SPID[0],
                    Spv2: res.goods[0].C_SPID[1],
                    Spv3: res.goods[0].C_SPID[2]
                })
            }
        }
        let salemodels = [],
            salemodel = null
        if (res.salemodel) { //是否有秒杀和积分
            res.salemodel = JSON.parse(res.salemodel)
            res.salemodel.map((item) => {
                if (item.IsFullSale === false) {
                    salemodels.push(item)
                }
            })
            salemodel = salemodels[0]
        }
        res.goods[0].N_NUM = 1
        that.setState({
            goodsInfo: res.goods[0],
            GoodsImgs: res.GoodsImgs,
            goodsgrupshop: res.goodsgrupshop,
            salemodel: salemodel,
            lvgg: res.lvgg,
        }, () => {
            if (callback) { callback() }
        })
    })
}
// 切换商品详情规格
function getGoodDetailLvgg(that, goodsInfo, spv, callback) {
    let str = `Spv1&GbId&ShopNo`
    let params = {
        bNo: '701b',
        GbId: goodsInfo.N_GB_ID,
        isGoodsImg: "1",
        Spv1: spv.Spv1 || '0',
        Spv2: spv.Spv2 || '0',
        Spv3: spv.Spv3 || '0',
        isgroupshop: that.state.isgroupshop || '0',
        mebno: getGlobalData('C_MB_NO'), //用户信息id
    }
    api.get(str, params).then((res) => {
        if (callback) { callback(res) }
    })
}
// 加入、减去购物车 800b   减少、编辑购物车 801
function changeCar(that, bNo, good, num, ljgm, callback) {
    const userInfo = Taro.getStorageSync('userInfo')
    let str = ``
    let params = {
        bNo: bNo,
        gid: good.ID || good.N_GOODS_ID,
        num: num,
        // goodsattr: that.state.goodsattr || '',
        mebno: userInfo.C_MB_NO,
        mkid: that.state.mkid || '', //促销活动编号
        mkcid: that.state.mkcid || '' //促销活动类型(1分时促销 2秒杀 3立减 4全场折扣 5积分活动)
    };

    if (bNo == 'GO0002') { //减少购物车
        params = {
            bNo: bNo,
            ShopNo: getGlobalData('SHOP_NO'),
            mebNo: userInfo.C_MB_NO,
            cartId: good.cartId,
            num: num,
            MD5: 'shopNo&mebNo&cartId&num'
        };
        lyServce.getS(params).then(({data})=>{
            base.showToast(data.msg)
            if (callback) { callback(data) }
            that.state.disabled = false
        })
        return;
    } else if (bNo == '801') { //减少购物车
        // str = `mebno&gid&num&mkid&mkcid&goodsattr&ShopNo`
        str = `mebno&gid&num&mkid&mkcid&ShopNo`
    } else if (bNo == 'GO0001') { //减少购物车
        // str = `mebno&gid&num&mkid&mkcid&goodsattr&ShopNo`
        str = `ShopNo&mebNo&goodsId&num`
        params = {
            bNo: bNo,
            ShopNo: getGlobalData('SHOP_NO'),
            mebNo: userInfo.C_MB_NO,
            goodsId: good.goodsId,
            num: num
        };
    } else { //加入购物车 800b
        str = `gid&num&mkid&mkcid&mebno&ShopNo`
        params['ljgm'] = ljgm //0:加入购物车1:立即购买
    }
    console.log(params)
    if (that.state.disabled) { return }
    that.state.disabled = true
    api.get(str, params).then((res) => {
        base.showToast(res.msg)
        if (callback) { callback(res) }
        that.state.disabled = false
    }).catch((err) => {
        base.showToast(err.msg, 'none')
        that.state.disabled = false
    })
}
// 删除购物车
function delCart(cartids, callback) {
    const str = `cartids&ShopNo`
    const params = {
        bNo: 803,
        cartids: cartids,
    }
    api.get(str, params, (res) => {
        if (callback) { callback(res) }
    })
}
// 获取购物车数量  805
function getCartNum(that, callback) {
    const userInfo = Taro.getStorageSync('userInfo')
    const str = `mebno&ShopNo`
    const params = {
        bNo: 805,
        mebno: userInfo.C_MB_NO,
    }
    api.get(str, params, function(res) {
        if (callback) { callback(res) }
        that.setState({
            cartNum: res.goodsnum
        })
    })
}
//  获取用户购物车列表 802  获取部分购物车列表
function getUserCart(that, cids, callback) {
    let str = cids ? `mebno&cids&ShopNo` : `mebno&ShopNo`
    const userInfo = Taro.getStorageSync('userInfo')
    // let params = {
    //     bNo: 802,
    //     mebno: userInfo.C_MB_NO,
    //     // isactive: '1'
    // }
    let params = {
        bNo: 'GO0003',
        shopNo:  getGlobalData('SHOP_NO'),
        mebNo: userInfo.C_MB_NO,
        MD5: 'shopNo&mebNo'
    }
    if (cids) {
        params['cids'] = cids
    }

    lyServce.getS(params).then(({data})=>{
        console.log(data)
        if (cids) {
            if (callback) { callback(data) }
        } else {
            // that.setState({ cartList: res.cart })
            if (callback) { callback(data.cartItems, data) }
        }
    }, function(res) {
        if (cids) {
            if (callback) { callback(data) }
        } else {
            // that.setState({ cartList: res.cart })
            if (callback) { callback(data.cartItems, data) }
        }
    })
    // api.get(str, params, function(res) {
       
    // })
}
// 设置购物车、分类商品列表 加减购物车数量
function setCartList(that, pages, index, bNo, types, callback) {
    let lists;
    if (pages == 'cart') { //购物车页面
        lists = that.state.cartList
    }
    if (pages == 'goodList') { //商品分类列表页面
        lists = that.state.goodList
    }
    if (bNo == '800b') { // +
        if (lists[index].STOCK <= lists.N_NUM) {
            base.showToast('商品库存不足了！')
            return
        }
    }
    if (bNo == 'GO0002') { // +
        if (lists[index].STOCK <= lists.num) {
            base.showToast('商品库存不足了！')
            return
        }
    }
    let nums = types == 'add' ? lists[index].num + 1 : lists[index].num - 1;
    changeCar(that, bNo, lists[index], nums, '0', (res) => {
        lists[index].num = res.cartnum
        let gid = lists[index].ID || lists[index].goodsId
        let cartId = ''
        if (res.cartnum == 0 && bNo == 'GO0002') {
            getUserCart(that, null, (res) => {
                res.map((item, i) => {
                    if (gid == item.goodsId) {
                        cartId = item.cartId
                    }
                })
                if (cartId != '') {
                    delCart(cartId, (r) => {
                        if (pages == 'cart') {
                            base.showToast('删除' + r.msg)
                        }
                    })
                }
                if (pages == 'cart') {
                    lists.splice(index, 1)
                    if (callback) { callback(lists) }
                }
                if (pages == 'goodList') {
                    that.setState({ goodList: lists })
                    if (callback) { callback(lists) }
                }
            })
        } else {
            if (pages == 'cart') {
                if (callback) { callback(lists) }
            }
            if (pages == 'goodList') {
                that.setState({ goodList: lists })
                if (callback) { callback(lists) }
            }
        }
    })
}
// 订单详情展示
function getOrderDetail(that, cids, callback) {
    const userInfo = Taro.getStorageSync('userInfo')
    if (cids != '') { //提交订单
        const str = `mebno&cids&ShopNo`
        const params = {
            bNo: 808,
            mebno: userInfo.C_MB_NO,
            cids: cids,
        }
        api.get(str, params, (res) => {
            if (res.posmethod) { //配送方式
                let flagPost = 0
                res.posmethod.map((item, i) => {
                    if (item.n_isdefault == 1) {
                        that.state.psmethod = item.c_psname
                        flagPost++
                    }
                })
                if (flagPost == 0) {
                    res.posmethod[0].n_isdefault = 1
                    that.state.psmethod = res.posmethod[0].c_psname
                }
            }
            if (res.Selflift) { // 门店自提列表
                res.Selflift.map((item, i) => {
                    item.def = i == 0 ? '1' : '0'
                })
            }
            // res.address = {C_ADDRESS : "新港中路397号",
            //         C_CITY : "广州市",
            //         C_CITY_CODE : "",
            //         C_COUNTY : "海珠区",
            //         C_MB_LONGITUDE : "113.325296,23.095369",
            //         C_MB_NAME : "张三",
            //         C_MB_NO : "1013755",
            //         C_MB_PHONE : "020-81167888",
            //         C_OPENID : null,
            //         C_PROVINCE : "广东省",
            //         C_SHOP_NO : "100276",
            //         C_ZIPCODE : "",
            //         N_ISDEFAULT : 1,
            //         N_MA_ID : 1713
            //     }

            // if (res.SaleActive) {
            //     res.SaleActive = JSON.parse(res.SaleActive)
            // }
            // if (res.address) {
            //     res.address.C_MB_LONGITUDE = res.address.C_MB_LONGITUDE.split(",")
            //     for (let i = 0; i < res.address.C_MB_LONGITUDE.length; i++) {
            //         if (typeof res.address.C_MB_LONGITUDE[i] == "string") {
            //             res.address.C_MB_LONGITUDE[i] = parseFloat(res.address.C_MB_LONGITUDE[i])
            //         }
            //     }
            //     that.setData({
            //         address: res.address,
            //         addid: res.address.N_MA_ID
            //     })
            // }
            // console.log("订单详情that.data.psmethod_lx: " + that.data.psmethod_lx)
            // //posmethodNo n_ps_lx	1商家配送 2骑士专送 3快递配送 4门店自提
            // if (!that.data.cart) {
            //     if (res.cart) {
            //         for (let i = 0; i < res.cart.length; i++) {
            //             res.cart[i].salemodel = null
            //             if (res.cart[i].saledata) {
            //                 for (let j = 0; j < res.cart[i].saledata.length; j++) {
            //                     if (res.cart[i].N_MARKING_CID == res.cart[i].saledata[j].SaleTypeNo) {
            //                         res.cart[i].salemodel = res.cart[i].saledata[j]
            //                     }
            //                 }
            //             }
            //         }
            //     }
            that.setState({
                cart: res.cart,
                posmethod: res.posmethod,
                psmethod: that.state.psmethod,
                postime: res.postime,
                selflift: res.Selflift, // 自提店铺地址列表
                selfliftSelect: res.Selflift[0], //当前选择的自提地址
                selfliftShow: that.state.psmethod == '上门自提' ? true : false, //上门自提列表是否显示
                address: res.address, //地址
                // checkedIndex: that.data.checkedIndex,
                // psmethod_lx: that.data.psmethod_lx
            }, () => {
                if (callback) { callback() }
            })
        })
    }
}
// 获取订单金额
function getOrderPrices(that, callback) {
    const userInfo = Taro.getStorageSync('userInfo')
    const params = {
        bNo: 420,
        mebno: userInfo.C_MB_NO,
        cids: that.state.cids, //购物车编号id
        yhqid: that.state.yhqid, //领取的优惠券id（n_mcr_id）
        psmethod: that.state.psmethod, //配送方式；数据类型：string（上门自提，骑士专送，快递配送，商家配送）
        isactive: that.state.isactive, //是否要参加促销活动(1参加，2不参加)
        isIntergral: that.state.intergralState, //积分 0不开启，1开启
        isBalance: that.state.balanceState, // 余额 0不开启，1开启
    }
    api.get('', params, (res) => {
            if (that.state.yhqid != '') {
                res.marketimg.map((item, i) => {
                    item.select = that.state.yhqid == item.MarketingCId ? true : false
                })
            }
            that.setState({
                refresh: false,
                marketimg: res.marketimg, //优惠券列表
                postmoney: res.Youfei, //运费
                orderyprice: res.allmoney, //商品金额
                orderprice: res.ordermoney, //实付款
                cxuserIntergral: res.cxuserIntergral, //单商品活动积分
                Intergral: res.Intergral,
                IntergralMoney: res.IntergralMoney,
                balance: res.balance,
                dbje: res.dbje,
                // ShoppingCardid:"0",
                // ShoppingMoney:0,
                // code:"100",
                // cqsje:0,
                // goodscxje:5.58,
                // mallcxje:0,
                // psground:"1",
                // qsje:0,
                // zkje:0,
            })
            if (callback) { callback() }
        })
        // if (that.state.psmethod_lx == "骑士专送") {
        //    if (that.state.qspostmoney) {//骑士配送运费；数据类型：string
        //       params['qspostmoney'] = that.state.qspostmoney
        //    }
        // }
        // if (that.data.switchIntergral) {
        //    params['isIntergral'] = '1'
        // } else {
        //    params['isIntergral'] = '0'
        // }
        // if (that.data.switchBalance) {
        //    params['isBalance'] = '1'
        // } else {
        //    params['isBalance'] = '0'
        // }
        // if (that.data.saleids) {//	活动编号
        //    params['saleids'] = that.data.saleids
        // }
        // if (that.data.psmethod_lx == "商家配送" || that.data.psmethod_lx == "骑士专送") {
        //    if (that.data.addid) {//	地址id；数据类型：int
        //       params['addid'] = that.data.addid
        //    }
        //    console.log("that.data.addid: " + that.data.addid)
        // }
        // console.log("that.data.psmethod_lx: " + that.data.psmethod_lx)
        // console.log("that.data.addid: " + that.data.addid)
        // app.remote('', params, function (res) {
        //    console.log("420结算价格：")
        //    console.log(res)
        //    if (res.marketimg) {
        //       for (let i = 0; i < res.marketimg.length; i++) {
        //          res.marketimg[i].MarketingBeginTime = res.marketimg[i].MarketingBeginTime.replace(/\-/g, ".")
        //          res.marketimg[i].MarketingEndTime = res.marketimg[i].MarketingEndTime.replace(/\-/g, ".")
        //       }
        //    }
        //    if (!that.data.prices) {
        //       that.setData({
        //          totalBalance: res.balance,
        //          totalIntergral: res.Intergral,
        //          IntergralMoney: res.IntergralMoney
        //       })
        //    }
        //    if (that.data.psmethod_lx == "商家配送" || that.data.psmethod_lx == "骑士专送") {
        //       //psground  0不在配送范围，1在配送范围,-1无法取到配送距离
        //       var txt = ""
        //       if (that.data.psmethod_lx == "商家配送") {
        //          txt = "地址不在商家配送范围"
        //       } else {
        //          txt = "地址不在骑士专送配送范围"
        //       }
        //       if (res.psground == "0") {
        //          wx.showModal({
        //             title: '提示',
        //             content: txt,
        //             showCancel: false
        //          })
        //       }
        //       that.setData({
        //          psground: res.psground
        //       })
        //    } else {
        //       psground: null
        //    }
        //    that.setData({
        //       prices: res,
        //       marketimg: res.marketimg, //卡券
        //       isShow: true
        //    })
        //    console.log(that.data.isShow)
        //    if (callback) {
        //       callback()
        //    }
        //    wx.hideLoading()
        // })
}
// 支付
function payment(orderno, callback, failback, comback) {
    console.log("orderno ======" + orderno)
    let env = process.env.TARO_ENV;
    if (env == 'weapp') {
        _weappPayment(orderno)
    } else if (env == 'alipay') {
        console.log('alipay -------')
        _alipayPayment(orderno)
    }
}
// 微信支付
function _weappPayment(orderno, callback, failback, comback) {
    const openid = Taro.getStorageSync('openid')
    const params = {
        bNo: 1501,
        orderno: orderno,
        openid,
    }
    api.get('', params).then((res) => {
        console.log(res)
        if (res.errCode == 0) {
            Taro.requestPayment({
                timeStamp: res.data.timeStamp,
                nonceStr: res.data.nonceStr,
                package: res.data.package,
                signType: res.data.signType,
                paySign: res.data.paySign,
                'success': function(data) {
                    console.log(data)
                    base.showToast('支付成功')
                    if (callback) { callback() } else {
                        setTimeout(function() {
                            Taro.navigateTo({ url: `/pages/payResult/payResult?result=0&&orderno=${orderno}` })
                        }, 1000)
                    }
                },
                'fail': function(fail) {
                    console.log(fail)
                    if (fail.errMsg == "requestPayment:cancel" || fail.errMsg == "requestPayment:fail cancel") {
                        base.showToast('您取消支付了', 'none')
                        if (failback) { failback() } else {
                            setTimeout(function() {
                                Taro.reLaunch({ url: '/pages/personal/personal' })
                            }, 1000);
                        }
                    } else {
                        base.showModal(fail.msg)
                    }
                }
            })
        } else {
            base.showModal(res.msg, false, () => {
                if (comback) { comback() } else { Taro.reLaunch({ url: '/pages/personal/personal' }) }
            })
        }
    }).catch((err) => {
        base.showModal(err.errMsg, null, () => {
            Taro.navigateBack()
        })
        Taro.hideLoading()
    })
}
// 支付宝支付
function _alipayPayment(orderno, callback) {
    const openid = Taro.getStorageSync('openid')
    const params = {
        OpenId: openid,
        OrderNo: orderno
    }
    api.postAlipay('/CreateOrder', params).then((res) => {
            my.tradePay({
                tradeNO: res.data.tradeNO, // 调用统一收单交易创建接口
                success: (_res) => {
                    console.log('tradeNO_res-----')
                    console.log(_res)
                    base.showToast(_res.memo)
                    if (_res.resultCode == '9000') {
                        if (callback) { callback() } else {
                            setTimeout(function() {
                                Taro.navigateTo({ url: `/pages/payResult/payResult?result=0&&orderno=${orderno}` })
                            }, 1000)
                        }
                    } else {
                        setTimeout(function() {
                            Taro.navigateTo({ url: `/pages/personal/personal` })
                        }, 1000)
                    }
                },
                fail: (_err) => {
                    console.log('tradeNO_err-----')
                    console.log(_err)
                    my.alert({
                        content: JSON.stringify(_err),
                    });
                },
                complete: () => {
                    Taro.hideLoading()
                }
            });
        }).catch((err) => {
            console.log(err)
            base.showModal(err.msg, null, () => {
                Taro.reLaunch({
                    url: '/pages/personal/personal'
                })
            })
        })
        // api.postAlipay('/CreateOrder',params,(res) => {
        //     my.tradePay({
        //         tradeNO: res.data.tradeNO, // 调用统一收单交易创建接口（alipay.trade.create），获得返回字段支付宝交易号trade_no
        //         success: (_res) => {
        //             console.log('tradeNO_res-----')
        //             console.log(_res)
        //             base.showToast(_res.memo)
        //             if(_res.resultCode == '9000'){
        //                 if (callback) { callback() }
        //                 else {
        //                     setTimeout(function () {
        //                         Taro.navigateTo({ url: `/pages/payResult/payResult?result=0&&orderno=${orderno}` })
        //                     }, 1000)
        //                 }
        //             }else{
        //                 setTimeout(function () {
        //                     Taro.navigateTo({ url: `/pages/personal/personal` })
        //                 }, 1000)
        //             }     
        //         },
        //         fail: (_err) => {
        //             console.log('tradeNO_err-----')
        //             console.log(_err)
        //             my.alert({
        //                 content: JSON.stringify(_err),
        //             });
        //         },
        //         complete: () => {
        //             Taro.hideLoading()
        //         }
        //     });
        // },(err) => {
        //     console.log(err)
        //     base.showModal(err.msg, null,() => {
        //         Taro.reLaunch({
        //             url: '/pages/personal/personal'
        //         })
        //     })
        // })
}
// 获取地址列表
function getAddressList(that, callback) {
    const userInfo = Taro.getStorageSync('userInfo')
    let str = `mebno&ShopNo`
    let params = {
        bNo: '1001',
        mebno: userInfo.C_MB_NO,
    }
    api.get(str, params, (res) => {
        that.setState({
            addressList: res.address,
            refresh: false
        }, () => {
            if (callback) { callback(res) }
        })
    })
}
// 添加地址
function addressAdd(that) {
    Taro.chooseAddress({
        success: function(res) {
            const openid = Taro.getStorageSync('openid')
            const userInfo = Taro.getStorageSync('userInfo')
            var address = {}
            address.C_MB_NAME = res.userName
            address.C_MB_PHONE = res.telNumber
            address.C_PROVINCE = res.provinceName
            address.C_CITY = res.cityName
            address.C_COUNTY = res.countyName
            address.C_ADDRESS = res.detailInfo
            const str = `mebno&province&city&county&addrid&name&phone&address&openid&ShopNo`;
            const params = {
                bNo: 1004,
                mebno: userInfo.C_MB_NO,
                province: res.provinceName,
                city: res.cityName,
                county: res.countyName,
                addrid: that.state.addrid || '',
                name: res.userName,
                phone: res.telNumber,
                address: res.detailInfo,
                openid: openid,
            }
            api.get(str, params, function(res) {
                res.LONGITUDE = res.LONGITUDE.split(",")
                for (let i = 0; i < res.LONGITUDE.length; i++) {
                    if (typeof res.LONGITUDE[i] == "string") {
                        res.LONGITUDE[i] = parseFloat(res.LONGITUDE[i])
                    }
                }
                address.C_MB_LONGITUDE = res.LONGITUDE
                console.log("选择地址：1004")
                console.log(res)
                that.setState({
                    address: address,
                    addrid: res.addrid
                })
                if (that.state.psmethod == "骑士专送") {

                } else {
                    getOrderPrices(that)
                    addressDefault(that, res.addrid)
                }
                //  console.log(that.data)
                //  if (that.data.psmethod_lx == "骑士专送") {
                //     console.log(address)
                //     console.log(11111111111111111111)
                //     knightDelivery(that, function () {
                //        getOrderDetail(that, that.data.cids)
                //        addressDefault(that, res.addrid)
                //     })
                //  } else {
                //     getOrderDetail(that, that.data.cids)
                //     addressDefault(that, res.addrid)
                //  }
            }, function(err) {
                console.log(err)
            })
        },
        fail: function(err) {
            if (err.errMsg != "chooseAddress:cancel" || err.errMsg != "chooseAddress:fail cancel") {
                Taro.getSetting({
                    success: (res) => {
                        if (!res.authSetting['scope.address']) { //没授权
                            wx.openSetting({
                                success: (res) => {}
                            })
                        }
                    }
                })
            }
        }
    })
}
// 设置默认地址
function addressDefault(maid, callback) {
    const userInfo = Taro.getStorageSync('userInfo')
    const str = `maid&mebno&ShopNo`
    const params = {
        bNo: 1005,
        maid: maid,
        mebno: userInfo.C_MB_NO,
    }
    api.get(str, params, (res) => {
        if (callback) { callback(res) }
    })
}
// 获取地址的通用接口
function getAddress(callback) {
    const bhjUrl = getGlobalData('bhjUrl')
    Taro.request({
        url: bhjUrl + '/shouyin_pay/getAllAreaInfo',
        method: 'GET',
        success: (res) => {
            const areaInfo = [],
                provinces = [],
                citys = [],
                countys = [];
            res.data.data.map((item, i) => {
                if (item.type == '1') {
                    provinces.push(item)
                }
                if (item.type == '2') {
                    citys.push(item)
                }
                if (item.type == '3') {
                    countys.push(item)
                }
            })
            areaInfo[0] = provinces
            areaInfo[1] = citys
            areaInfo[2] = countys
            setGlobalData('areaInfo', areaInfo)
            if (callback) { callback(areaInfo, res.data.data) }
        },
        fail: (err) => {
            console.log(err)
        }
    })
}
// 获取积分商品列表
function getExchangeList(that, callback) {
    const str = `ShopNo&pageindex&pagesize`
    let pagesize = getGlobalData('pagesize')
    if (that.state.gids) {
        let gidsArr = that.state.gids.split(',')
        pagesize = gidsArr.length
    }
    let params = {
        bNo: 1302,
        pageindex: that.state.pageindex,
        pagesize: pagesize,
        gids: that.state.gids,
    }
    let goodLists = []
    api.get(str, params, (res) => {
        if (!res.Gift) { res.Gift = [] }
        goodLists = that.state.pageindex == 1 ? res.Gift : that.state.goodList.concat(res.Gift)
        that.state.hasEd = res.Gift.length < pagesize ? true : false
        that.setState({
            goodList: goodLists,
            hasList: true,
            hasEd: that.state.hasEd
        })
        if (callback) { callback(goodLists) }
    })
}
// 获取拼团商品列表
function getPintuanList(that, callback) {
    const str = `ShopNo`
    let pagesize = getGlobalData('pagesize')
    if (that.state.gids) {
        let gidsArr = that.state.gids.split(',')
        pagesize = gidsArr.length
    }
    let params = {
        bNo: 611,
        pagesize: pagesize,
        pageindex: that.state.pageindex,
        gids: that.state.gids
    }
    let goodLists = []
    api.get(str, params, (res) => {
        if (!res.goodsList) { res.goodsList = [] }
        goodLists = that.state.pageindex == 1 ? res.goodsList : that.state.goodList.concat(res.goodsList)
        that.state.hasEd = res.goodsList.length < pagesize ? true : false
        that.setState({
            goodList: goodLists,
            hasList: true,
            hasEd: that.state.hasEd
        })
        if (callback) { callback(goodLists) }
    })
}
// 提交预约信息
function subscribe(that, callback, errback, comback) {
    const date = new Date();
    let ydtime = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`
    const userInfo = Taro.getStorageSync('userInfo')
    const str = `mebno&cids&amount&ydname&ydphone&ydtime&Remarks&Sex&mebcount&ShopNo`
    const params = {
        bNo: 424,
        mebno: userInfo.C_MB_NO,
        cids: "",
        amount: 0,
        ydname: that.state.ydname,
        ydphone: that.state.ydphone,
        ydtime: ydtime,
        Remarks: that.state.remarks,
        Sex: 2,
        mebcount: that.state.mebcount || 0,
    }
    api.get(str, params, (res) => {
        if (callback) { callback(res) }
    }, (err) => {
        if (errback) { errback(err) }
    }, () => {
        if (comback) { comback() }
    })
}
// 获取验证码
function getCode(that, callback) {
    if (that.state.codeDisabled) { return }
    that.setState({ codeDisabled: true })
    base.getCodeTimer(120, that, function(timer) {
        const str = `phone&ShopNo`
        const params = {
            bNo: 102,
            phone: that.state.phoneNum,
        }
        api.get(str, params, function(res) {
            if (res.code == '101') {
                base.showToast(res.msg, 'none')
            }
            if (callback) { callback(res, timer) }
        }, function(res) {
            base.showToast(res.msg)
        })
    })
}
// 跳转路径
function comNavTo(modelId, linktype, linkparam) {
    // console.log(linkparam)
    if (!linkparam) { linkparam = '' }
    if (linkparam.indexOf('=') != -1) {
        linkparam = linkparam.split('=')
        linkparam = linkparam[1]
    }
    let _goodList = `/pages/goodList/index?gcid=${linkparam}&modelId=${modelId}` // 商品列表 - 商品分类 702b
    let _goodListMarketing = `/pages/goodListMarketing/index?modelId=${modelId}` // 商品列表 - 积分
    let _goodsDatil = `/pages/goodsDatil/index?goodsId=${linkparam}` // 商品详情
    let _goodsDatilExchange = `/pages/goodsDatilExchange/index?goodsId=${linkparam}` // 商品详情 - 积分
    let _couponPage = `/pages/couponPage/index` // 优惠券
    let _searchList = `/pages/searchList/index` // 搜索列表
    let _articleList = `/pages/articleList/index?goodsId=${linkparam}` // 文章列表
    let _articleDetail = `/pages/articleDetail/index?ntid=${linkparam}` // 文章详情
        // 商品
    if (modelId == '27') { // 商品-单商品-横幅
        if (linktype == '1') {
            Taro.navigateTo({ url: _goodsDatil })
        } else if (linktype == '2') {
            Taro.navigateTo({ url: _goodList })
        }
    } else if (modelId == '26') { // 商品-多商品-积分商品
        if (linktype == 1) { // 列表
            Taro.navigateTo({ url: _goodListMarketing })
        } else {
            Taro.navigateTo({ url: _goodsDatilExchange })
        }
        // 信息
    } else if (modelId == '7' || modelId == '28') { // 单条新闻
        if (modelId == '28') {
            Taro.navigateTo({ url: _articleDetail })
        }


        // 营销
    } else if (modelId == '3') { // 营销-优惠券
        Taro.navigateTo({ url: _couponPage })
    } else if (modelId == '61') { // 营销-拼团
        if (linktype == 1) { // 列表
            Taro.navigateTo({ url: _goodListMarketing })
        } else if (linktype == '0') {
            Taro.navigateTo({ url: `${_goodsDatil}&SaleTypeNo=pinTuan` })
        }
        // 店铺相关

        // 公共组件
        else if (modelId == '51' || modelId == '52' || modelId == '53' || modelId == '54' || modelId == '55') { // 公共组件-栏目入口-导航样式1-5   只做了商品列表分类跳转
            if (linktype == '3') {
                Taro.navigateTo({ url: _goodList })
            }
        } else if (modelId == '31' || modelId == '32' || modelId == '33') { // 公共组件-栏目入口-商品栏目样式1-3
            Taro.navigateTo({ url: _goodList })
        }

        // 页面
    } else if (modelId == '0' || modelId == '14') { // 搜索列表
        Taro.navigateTo({ url: _searchList })
    } else if (modelId == '1') { // banner
        if (linktype == 1) { // 商品详情
            Taro.navigateTo({ url: _goodsDatil })
        } else if (linktype == 2) { // 商品列表
            Taro.navigateTo({ url: _goodList })
        }
    }
}